package com.karson.service.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.karson.common.dto.FileRecordDTO;
import com.karson.common.exception.AsmrException;
import com.karson.common.model.Subtitles;
import com.karson.common.model.TrackInfo;
import com.karson.common.model.TrackRate;
import com.karson.common.request.TrackRequest;
import com.karson.common.response.CommonResult;
import com.karson.common.response.TrackResponse;
import com.karson.common.util.AsmrUtil;
import com.karson.common.util.FileTypeUtil;
import com.karson.service.service.*;
import com.karson.service.dao.TrackInfoMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
* @author ZKS
* &#064;description  针对表【ar_track_info(声音信息)】的数据库操作Service实现
* &#064;createDate  2025-08-14 14:42:37
 */
@Service
public class TrackInfoServiceImpl extends ServiceImpl<TrackInfoMapper, TrackInfo>
    implements TrackInfoService{

    @Autowired
    private TrackInfoMapper trackInfoMapper;
    @Autowired
    private StorageServiceFactory storageServiceFactory;
    @Autowired
    private TrackRateService trackRateService;
    @Autowired
    private SubtitlesService subtitlesService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveAlbumInfo(List<TrackRequest> trackRequest) {
        List<TrackRequest> list = trackRequest.stream().filter(track -> {
            LambdaQueryWrapper<TrackInfo> trackQueryWrapper = new LambdaQueryWrapper<>();
            trackQueryWrapper.eq(TrackInfo::getAlbumId, track.getAlbumId());
            trackQueryWrapper.eq(TrackInfo::getTrackTitle, track.getTrackTitle());
            TrackInfo one = getOne(trackQueryWrapper);
            return one == null;
        }).toList();
        if (list.isEmpty()) {
            return false;
        }
        List<TrackInfo> trackList = list.stream().map(track -> BeanUtil.copyProperties(track, TrackInfo.class)).toList();
        return this.saveBatch(trackList);
    }

    @Override
    public List<TrackResponse> getTrackInfo(Integer albumId) {
        return trackInfoMapper.getTrackInfo(albumId);
    }

    @Override
    public Boolean uploadFile(HttpServletRequest request, MultipartFile file, String folder, Integer fileType, Integer trackId) throws IOException {
        TrackInfo trackInfo = super.getById(trackId);
        if (trackInfo == null) {
            throw new AsmrException("查无改乐曲，请勿上传附件");
        }
        String filename = file.getOriginalFilename();
        //判断是否登录
        boolean login = StpUtil.isLogin();
        String md5 = SecureUtil.md5(file.getInputStream());
        synchronized (md5.intern()) {
            String dateFormat = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
            assert filename != null;
            String objectName = (folder == null ? "default" : folder) + "/" +
                    dateFormat + "/" + md5 + "." + FileTypeUtil.getFileSuffix(filename);
            String storageType = AsmrUtil.getStorageTypeFromRequest(request);
            IStorageService storageService = storageServiceFactory.getStorageService(storageType);
            FileRecordDTO fileRecordDTO = storageService.uploadFile(file, md5, objectName, login);
            boolean isAudio = FileTypeUtil.bAudioFileType(filename);
            if (isAudio) {
                TrackRate trackRate = new TrackRate();
                trackRate.setTrackId(trackId);
                trackRate.setMediaSize(file.getSize());
                trackRate.setMediaFileName(filename);
                trackRate.setMediaType(file.getContentType());
                trackRate.setMediaUrl(fileRecordDTO.getAccessUrl());
                trackRate.setMediaFileId(fileRecordDTO.getFileIdentifier());
                trackRateService.save(trackRate);
            }
            boolean isSub = FileTypeUtil.bSubtitleFileType(filename);
            if (isSub) {
                Subtitles subtitles = new Subtitles();
                subtitles.setFilePath(fileRecordDTO.getAccessUrl());
                subtitles.setFileFormat(file.getContentType());
                subtitles.setFileName(file.getOriginalFilename());
                subtitles.setTrackId(trackId);
                subtitles.setAlbumId(trackInfo.getAlbumId());
                subtitlesService.save(subtitles);
            }
            return true;
        }
    }


}




